from __future__ import print_function

import base64
import requests
import cv2
import pycurl
import json
from PIL import Image
import numpy as np
import tensorflow as tf
from multiprocessing import Process
from threading import Thread,active_count
import io

np.set_printoptions(threshold=np.inf)

SERVER_URL = 'http://192.168.1.211:8501/v1/models/porn_inceptionv4_tf_gpu:predict'
# SERVER_URL = 'http://192.168.1.50:8000/v1/models/lpr:predict'
# SERVER_URL = 'http://192.168.1.50:8002/v1/models/lpr:predict'
model_path = "E:/working/TF_Slim_classification-master/lpr_lprnet/12"
img_file = 'E:\datasets\porndata\lqbz/Ptq7rwD.jpg'
# img_file = '000020.png'
json_file = '../hddlDetect.json'


def model_cli_http(request_method='requests'):
    imgc = cv2.imread(img_file)
    # imgc.astype(np.int8)
    # cv2.imshow('a', imgc)
    # img = cv2.normalize(img,dst, alpha=None, beta=None,)
    imgc = cv2.resize(imgc, (299,299))  # gbr  (width, height)
    # cv2.imshow('a', imgc)
    # imgc = imgc.transpose((2,0,1))
    # imgc = cv2.cvtColor(imgc, cv2.COLOR_BGR2RGB)
    # imgc = imgc.reshape(( 1,299, 299,3))
    # cv2.imshow('a',imgc[0])
    # cv2.waitKey(0)

    if request_method == 'requests':
        data_obj = {"signature_name": "porn_detect", "inputs": [imgc.tolist()]}
        # data_obj = {"signature_name": "aaa", "inputs": [imgc.tolist()] }

        data_json = json.dumps(data_obj)


        res = requests.post(SERVER_URL, data=data_json)
        print(res.text)
        # print(np.array(res.json()["outputs"]["detector/yolo-v3/Conv_6/BiasAdd/YoloRegion"]).shape)
        def fun(SERVER_URL):
            for i in range(10):
                res = requests.post(SERVER_URL, data=data_json)
                print(res.text)

        th_list = []
        for i in range(1,7):
            pass
            # t = Thread(target=fun,args=(SERVER_URL%i,))
            # th_list.append(t)
            # t.run()


        from time import sleep
        # sleep(1)

        # for t in th_list:
        #     t.run()
        # print(np.array(res.json()["outputs"]["detector/yolo-v3/Conv_6/BiasAdd/YoloRegion"]).shape)
    else:
        # sys.open
        # with open(img_file,'rb') as f:
          # byte_data = f.read()

        # pil.image.open
        # data = Image.open(img_file)
        # buffer = io.BytesIO()
        # data.save(buffer,format='JPEG')
        # byte_data = buffer.getvalue()
        # opencv
        # data = cv2.imread(img_file)
        # byte_data = cv2.imencode('.jpg', data)[1]

        jpeg_bytes = base64.b64encode(imgc).decode("utf8")
        predict_request = '{"signature_name":"porn_detect","instances":[{"b64":"%s"}]}' % jpeg_bytes
        # predict_request = json.dumps(predict_request,)
        res = requests.post(SERVER_URL, data=predict_request)
        print(res.text)

        # c = pycurl.Curl()
        # c.setopt(pycurl.URL, SERVER_URL)
        # c.setopt(pycurl.POSTFIELDS, predict_request)
        # c.perform()




    # print(c.fp.getvalue())

    #  # Send few requests to warm-up the model.
    # for _ in range(3):
    #     response = requests.post(SERVER_URL, data=predict_request)
    #     response.raise_for_status()
    #
    #  # Send few actual requests and report average latency.
    # total_time = 0
    # num_requests = 10
    # response = requests.post(SERVER_URL, data=predict_request)
    # print(response.json())
    # for _ in range(num_requests):
    #   response = requests.post(SERVER_URL, data=predict_request)
    #   response.raise_for_status()
    #   total_time += response.elapsed.total_seconds()
    #   prediction = response.json()['predictions'][0]
    #
    #   # print('Prediction class: {}, avg latency: {} ms'.format(
    #   #     prediction['classes'], (total_time*1000)/num_requests))


if __name__ == '__main__':
    model_cli_http()
